package gov.pbc.gx.nn.pz.impl;

import gov.pbc.gx.nn.pz.dao.ZdkywtzDao;
import gov.pbc.gx.nn.pz.entity.HcZdkywtz;
import gov.pbc.gx.nn.pz.entity.HcpzXY;
import gov.pbc.gx.nn.pz.entity.PzFont;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.variant.Record;
import com.bstek.dorado.web.DoradoContext;

@Component("zdkywtzPR")
public class ZdkywtzPR {

	private Integer PZ_CODE_ = 4;
	private static final Integer Font_Size = 16;

	@Resource
	@Autowired
	private ZdkywtzDao hczdkywtzDao;

	@Transactional
	@DataProvider
	public Record getZdkywtzs() {
		try {
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				return null;
			if (loginuser.getDepts() == null
					|| loginuser.getDepts().size() <= 0)
				return null;
			Record record = new Record();
			record.put("pzdate", new Date());
			Collection<HcZdkywtz> lists = hczdkywtzDao.getMuByDeptName();
			if (lists.isEmpty()) {
				HcZdkywtz e = new HcZdkywtz();
				e.setPzDate(new Date());
				e.setPzTemplate("新建模板");
				lists.add(e);
				record.put("zdkywtz", lists);
			} else {
				for(HcZdkywtz zdk:lists){
					zdk.setPzDate(new Date());
				}
				record.put("zdkywtz", lists);
			}
			List<HcpzXY> zdkywtzXYs = hczdkywtzDao.getHcZdkywtzXYs(PZ_CODE_);
			if (zdkywtzXYs != null && !zdkywtzXYs.isEmpty()) {
				record.put("pys", zdkywtzXYs);
			} else {
				zdkywtzXYs = new ArrayList<HcpzXY>();
				HcpzXY zdkywtzXY = new HcpzXY();

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("页边距", 50, 50, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setId(UUID.randomUUID().toString());
				zdkywtzXY.setProperty("年", 260, 72, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("月", 342, 72, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("日", 402, 72, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				// zdkywtzXY = new HcpzXY();
				// zdkywtzXY.setProperty("流水号", 560, 72);
				// zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("原业务流水号", 115, 103, 14);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("错误值", 125, 148, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("调整值", 455, 148, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("错误日期", 490, 103, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("调整说明", 125, 342, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				// zdkywtzXY = new HcpzXY();
				// zdkywtzXY.setProperty("主管审批", 125, 385);
				// zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("附件数量", 704, 245, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("金额错误", 124, 208, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("利率错误", 454, 208, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("账号错误", 125, 252, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("日期错误", 454, 252, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);

				zdkywtzXY = new HcpzXY();
				zdkywtzXY.setProperty("其他错误", 125, 286, Font_Size);
				zdkywtzXYs.add(zdkywtzXY);
			}
			record.put("pys", zdkywtzXYs);
			return record;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void setImageData(Graphics2D graphics, Map<String, Object> param) {
		try {
			HcZdkywtz hcZdkywtz = (HcZdkywtz) param.get("zdkywtz");

			Date pzdate = (Date) param.get("pzdate");

			int pyx = (int) Integer.parseInt(param.get("x").toString());
			int pyy = (int) Integer.parseInt(param.get("y").toString());

			String fontzh = param.get("cnFont").toString();
			String fonten = param.get("numFont").toString();

			graphics.setBackground(Color.WHITE);
			graphics.setColor(Color.BLACK);
			// Font zhFont = new Font(fontzh, Font.PLAIN, 16);
			// Font enFont = new Font(fonten, Font.PLAIN, 16);
			// Font lshFont = new Font(fonten, Font.PLAIN, 14);

			List<HcpzXY> hczdkywtz = (List<HcpzXY>) param.get("pys");

			for (HcpzXY pym : hczdkywtz) {

				int x = pym.getX() + pyx;
				int y = pym.getY() + pyy;
				int size = pym.getFontSize();
				String lable = pym.getLabel();
				// System.out.println(lable);
				if (pzdate != null) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(pzdate);

					if (lable.equals("年")) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%04d",
										calendar.get(Calendar.YEAR)), x, y);
					}
					if (lable.equals("月")) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%02d",
										calendar.get(Calendar.MONTH) + 1), x, y);
					}
					if (lable.equals("日")) {
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						graphics.drawString(
								String.format("%02d",
										calendar.get(Calendar.DATE)), x, y);
					}

				}
				if (hcZdkywtz != null) {
					// if (lable.equals("流水号")) {
					// if (hcZdkywtz.getSerialnumber() != null) {
					// graphics.setFont(enFont);
					// graphics.drawString(hcZdkywtz.getSerialnumber(), x,
					// y);
					// }
					// }
					if (lable.equals("原业务流水号")) {
						if (hcZdkywtz.getOldSerialNumber() != null) {
							Font lshFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(lshFont);
							graphics.drawString(hcZdkywtz.getOldSerialNumber(),
									x, y);
						}
					}
					if (lable.equals("错误日期")) {
						if (hcZdkywtz.getErrorDate() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							Calendar calendar = Calendar.getInstance();
							calendar.setTime(hcZdkywtz.getErrorDate());
							graphics.drawString(
									String.format("%04d",
											calendar.get(Calendar.YEAR)), x, y);
							graphics.drawString(
									String.format("%02d",
											calendar.get(Calendar.MONTH) + 1),
									x + 75, y);
							graphics.drawString(
									String.format("%02d",
											calendar.get(Calendar.DATE)),
									x + 125, y);
						}
					}
					if (lable.equals("错误值")) {
						if(hcZdkywtz.getErrorValue()==null){
							return;
						}
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						DecimalFormat myformat = new DecimalFormat();
						myformat.applyPattern("##,###.00");
						String chars = myformat.format(hcZdkywtz
								.getErrorValue());
						if (hcZdkywtz.getErrorIssign() == 0) {
							chars = ("¥" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getErrorIssign() == 1) {
							chars = ("HKD" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getErrorIssign() == 2) {
							chars = ("USD" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getErrorIssign() == 3) {
							graphics.drawString(chars, x, y);
						}

					}

					if (lable.equals("调整值")) {
						if(hcZdkywtz.getUpdateValue()==null){
							return;
						}
						Font enFont = new Font(fonten, Font.PLAIN, size);
						graphics.setFont(enFont);
						DecimalFormat myformat = new DecimalFormat();
						myformat.applyPattern("##,###.00");
						String chars = myformat.format(hcZdkywtz
								.getUpdateValue());
						if (hcZdkywtz.getUpdateIssign() == 0) {
							chars = ("¥" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getUpdateIssign() == 1) {
							chars = ("HKD" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getUpdateIssign() == 2) {
							chars = ("USD" + chars);
							graphics.drawString(chars, x, y);
						}
						if (hcZdkywtz.getUpdateIssign() == 3) {
							graphics.drawString(chars, x, y);
						}

					}
					if (lable.equals("附件数量")) {
						if (hcZdkywtz.getAttachmentCount() != null) {
							Font enFont = new Font(fonten, Font.PLAIN, size);
							graphics.setFont(enFont);
							graphics.drawString(String.valueOf(hcZdkywtz
									.getAttachmentCount()), x - 3, y);
						}
					}
					if (lable.equals("金额错误")) {
						if (hcZdkywtz.getErrorMoney() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							String[] nums = hcZdkywtz.getErrorMoney()
									.split(",");
							String click = "√";
							if (nums[0].equals("1")) {
								graphics.drawString(click, x - 2, y + 1);
							}
							if (nums[1].equals("1")) {
								graphics.drawString(click, x + 77, y + 1);
							}
							if (nums[2].equals("1")) {
								graphics.drawString(click, x + 156, y + 1);
							}
						}
					}
					if (lable.equals("利率错误")) {
						if (hcZdkywtz.getErrorLilv() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							String[] nums = hcZdkywtz.getErrorLilv().split(",");
							String click = "√";
							if (nums[0].equals("1")) {
								graphics.drawString(click, x - 4, y + 1);
							}
							if (nums[1].equals("1")) {
								graphics.drawString(click, x + 80, y + 1);
							}
							if (nums[2].equals("1")) {
								graphics.drawString(click, x + 164, y + 1);
							}
						}
					}
					if (lable.equals("账号错误")) {
						if (hcZdkywtz.getErrorUsername() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);

							String click = "√";
							if (hcZdkywtz.getErrorUsername().equals("1")) {
								graphics.drawString(click, x - 2, y + 1);
							}

						}
					}
					if (lable.equals("日期错误")) {
						if (hcZdkywtz.getErrorDateclass() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							String[] nums = hcZdkywtz.getErrorDateclass()
									.split(",");
							String click = "√";
							if (nums[0].equals("1")) {
								graphics.drawString(click, x - 4, y + 1);
							}
							if (nums[1].equals("1")) {
								graphics.drawString(click, x + 134, y + 1);
							}
						}
					}
					if (lable.equals("其他错误")) {
						if (hcZdkywtz.getErrorOther() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							String[] nums = hcZdkywtz.getErrorOther()
									.split(",");
							String click = "√";
							if (nums[0].equals("1")) {
								graphics.drawString(click, x - 2, y + 1);
							}
							if (nums[1].equals("1")) {
								graphics.drawString(click, x + 112, y + 1);
							}
							if (nums[2].equals("1")) {
								graphics.drawString(click, x + 226, y + 1);
							}
							if (nums[3].equals("1")) {
								graphics.drawString(click, x + 340, y + 1);
							}
							if (nums[4].equals("1")) {
								graphics.drawString(click, x - 2, y + 21);
							}
							if (nums[5].equals("1")) {
								graphics.drawString(click, x + 112, y + 21);
							}
							if (nums[6].equals("1")) {
								graphics.drawString(click, x + 226, y + 21);
							}
							if (nums[7].equals("1")) {
								graphics.drawString(click, x + 340, y + 21);
							}
							if (nums[8].equals("1")) {
								graphics.drawString(click, x + 453, y + 21);
							}
						}
					}
					if (lable.equals("调整说明")) {
						if (hcZdkywtz.getRecaption() != null) {
							Font zhFont = new Font(fontzh, Font.PLAIN, size);
							graphics.setFont(zhFont);
							graphics.drawString(
									String.valueOf(hcZdkywtz.getRecaption()),
									x, y - 3);
						}
					}
					// if (lable.equals("主管审批")) {
					// if (hcZdkywtz.getSupApproval() != null) {
					// graphics.setFont(enFont);
					// graphics.drawString(
					// String.valueOf(hcZdkywtz.getSupApproval()),
					// x, y-3);
					// }
					// }
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Expose
	public String getPrintImageAll(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", 0);
			param.put("y", 0);
			BufferedImage imagepz = ImageIO.read(new File(DoradoContext
					.getCurrent().getServletContext()
					.getRealPath("pz/zdkywtz.jpg")));
			Graphics2D graphicspz = (Graphics2D) imagepz.getGraphics();
			setImageData(graphicspz, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/all_" + loginuser.getUsername() + ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext
					.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagepz, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public String getPrintImageData(Map<String, Object> param) {
		try {
			if (param == null)
				return null;
			IUser loginuser = ContextHolder.getLoginUser();
			if (loginuser == null)
				throw new NoneLoginException("您未登录，请刷新页面后重试！！");
			param.put("x", -33);
			param.put("y", -37);
			BufferedImage imagedata = ImageIO.read(new File(DoradoContext
					.getCurrent().getServletContext()
					.getRealPath("pz/zdkywtz.jpg")));
			// System.out.println(imagepz.getWidth()*1.0/96.0*24.5);
			// BufferedImage imagedata= new BufferedImage(imagepz.getWidth(),
			// imagepz.getHeight(), imagepz.getType());
			Graphics2D graphicsdata = (Graphics2D) imagedata.getGraphics();
			graphicsdata.setBackground(Color.WHITE);

			// 打印背景图片
			graphicsdata.clearRect(0, 0, imagedata.getWidth(),
					imagedata.getHeight());
			setImageData(graphicsdata, param);
			// ByteArrayOutputStream bytestreampz=new ByteArrayOutputStream();
			String filename = "pz/temp/data_" + loginuser.getUsername()
					+ ".jpg";
			FileOutputStream fo = new FileOutputStream(new File(DoradoContext
					.getCurrent().getServletContext().getRealPath(filename)));
			ImageIO.write(imagedata, "jpg", fo);
			fo.flush();
			fo.close();
			// String
			// str="data:image/png;base64,"+Base64.encodeBase64String(bytestreampz.toByteArray());
			// System.out.println(str.length()+","+bytestreampz.toByteArray().length);
			return filename;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

	@Expose
	public Map<String, Object> getUserInfo() {
		IUser loginuser = ContextHolder.getLoginUser();
		Map<String, Object> userinfo = new HashMap<String, Object>();
		if (loginuser == null) {
			userinfo.put("cname", "");
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("cname", loginuser.getCname());
		if (loginuser.getDepts() == null || loginuser.getDepts().size() <= 0) {
			userinfo.put("dept", "");
			return userinfo;
		}
		userinfo.put("dept", loginuser.getDepts().get(0).getName());
		return userinfo;
	}

	@DataProvider
	public Collection<HcZdkywtz> getTypeByGroup() {
		return hczdkywtzDao.getOneGroupByType();

	}

	@SuppressWarnings("unused")
	@DataProvider
	public Collection<HcZdkywtz> getTepementNameByType(Map<String, Object> param) {
		if (param == null) {
			return null;
		}
		String type = (String) param.get("type");
		return hczdkywtzDao.getCoByType(type);
	}

	@Expose
	public HcZdkywtz ajaxselectOneByTypeAndTemplate(Map<String, Object> param) {

		String type = (String) param.get("type");
		String pzTemplate = (String) param.get("pzTemplate");
		if (type == null || pzTemplate == null) {
			return null;
		}
		return hczdkywtzDao.selectOneByTypeAndTemplate(type, pzTemplate);

	}

	@DataProvider
	public List<Record> getFonts() {
		return hczdkywtzDao.getFonts();

	}

	@DataProvider
	public PzFont getFont() {
		return hczdkywtzDao.getFont(PZ_CODE_);
	}

	@Transactional
	@DataResolver
	public void saveZdkywtz(HcZdkywtz hcZdkywtz) {
		hczdkywtzDao.saveZdkywtz(hcZdkywtz);
	}

	@Transactional
	@DataResolver
	public void saveZdkywtzXY(Collection<HcpzXY> hczdkywtz) {
		hczdkywtzDao.saveZdkywtzXY(hczdkywtz);

	}

	@Transactional
	@DataResolver
	public void saveFont(PzFont pzFont) throws Exception {
		hczdkywtzDao.updateFont(pzFont);
	}

	@Expose
	public void deleteTemplateById(String id) {
		if (StringUtils.isEmpty(id)) {
			return;
		}
		hczdkywtzDao.deleteTemplateById1(id);

	}


	@Expose
	public boolean updateTempalteName(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String pzTemplate = (String) parameter.get("pzTemplate");
		return hczdkywtzDao.updateTemplateNameDao(pzTemplate, id);
	}

	@Expose
	public boolean updateTempalteType(Map<String, Object> parameter) {
		String id = (String) parameter.get("id");
		String type = (String) parameter.get("type");
		return hczdkywtzDao.updateTemplateTypeDao(type, id);
	}

}